/**
 * 
 */
package com.jjt.kiki.other;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @author jjtEatJava
 *
 */
public class DownLoadFile {
	//根据url和网页类型生成需要保存的网页的文件名，去除url中的非文件名字符
	public String getFileNameByUrl(String url,String contentType) {
		//移除http
		url=url.substring(7);
		//text/html类型
		if(contentType.indexOf("html")!=-1) {
			url=url.replaceAll("[\\?/:*|<>\"]","_")+".html";
			return url;
		}else {//如application/pdf类型
			return url.replaceAll("[\\?/:*|<>\"]","_")+"."+contentType.substring(contentType.lastIndexOf("/")+1);
		}
	}
	//保存网页字节数组到本地，filePath为要保存的文件的相对地址
	private void saveToLocal(HttpEntity entity,String filePath) {
		try {
			OutputStream out =new FileOutputStream(new File(filePath));
			InputStream in = entity.getContent();
			byte[] b = new byte[1024];
			while(in.read(b)!=-1)
				out.write(b, 0, b.length);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}
	//下载URL指向的网页
	public String downloadFile(String url) {
		if(!url.startsWith("http://www.csdn.net/article/2"))
			return null;
		System.out.println(url);
		String filePath=null;
		//1.生成httpClient对象并设置参数
		CloseableHttpClient hc = HttpClients.createDefault();
		//2.设置链接
		HttpGet get = new HttpGet(url);
		//3.设置链接超时5s
		RequestConfig requestConfig = RequestConfig.custom()  
		        .setConnectTimeout(5000).build(); 
		get.setConfig(requestConfig);
		
		try {
			CloseableHttpResponse response = hc.execute(get);
			int statusCode =response.getStatusLine().getStatusCode();
			//判断访问状态码
			if(statusCode!=HttpStatus.SC_OK) {
				System.out.println("请求失败："+response.getStatusLine());
				filePath=null;
			}
			//根据网页url生成保存时的文件名
			filePath = "H:\\temp\\"+this.getFileNameByUrl(url, response.getHeaders("Content-Type")[0].getValue());
			this.saveToLocal(response.getEntity(), filePath);
		} catch (IOException e) {
			// 
			e.printStackTrace();
		}finally {
			try {
				hc.close();
			} catch (IOException e) {
				// 
				e.printStackTrace();
			}
		}
		return filePath;
	}
	
}
